/**
 * Copyright (C), 2020, Y2 T205
 * FileName: StockReleaseListener
 * Author: Lenovo
 * Date: 2020-05-29 21:11
 * Description:
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */


package com.atguigu.gulimall.ware.listener;



import com.atguigu.common.to.StockLockedTo;

import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.gulimall.ware.service.WareSkuService;

import com.rabbitmq.client.Channel;


import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author Lenovo
 * @create 2020-05-29
 * @since 1.0.0
 */
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    //    库存自动解锁
//    下订单成功，库存锁定成，接下来的业务调用失败，导致订单回滚，之前锁定的库存就要自动解锁
//    只要解锁库存的消息失败，一定要告诉废物解锁失败
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message,Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息");
        try {


            wareSkuService.unlockStock(to);
            //不是批量回复
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        } catch (Exception e) {
            //重新回队
          channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
        }
    }

    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo,Message message, Channel channel) throws IOException {
        System.out.println("订单关闭准备解锁库存");
        try {
            wareSkuService.unlockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
        catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }
}
